package com.chwn.curiousdiary.ui.user.activity;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.api.IUserApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.User;
import com.chwn.harulib.base.BaseActivity;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.chwn.harulib.mvp.rx.RxSchedulers;
import com.chwn.harulib.util.NetUtils;
import com.gyf.barlibrary.ImmersionBar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;

/**
 * Created by Myshikin on 2017/4/7.
 */

public class MessageDetailActivity extends BaseActivity {

    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.progress)
    ProgressBar mProgress;
    private WebView mWebView;
    private String APP_CACAHE_DIRNAME = "cache";

    private String messageUrl;
    private String messageId;
    private boolean isFirst = true;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_message;
    }

    @Override
    protected void initData() {
        super.initData();
        messageUrl = getIntent().getStringExtra(Constant.MESSAGE_URL);
        messageId = getIntent().getStringExtra(Constant.MESSAGE_ID);
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        setTitleText("消息详情");
        initnavigationBarColor(-1);
        mProgress.setVisibility(View.VISIBLE);
        mProgress.setMax(100);
        mWebView = new WebView(this);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        mWebView.setLayoutParams(layoutParams);
        flContent.addView(mWebView);
        initWebView();
        mWebView.loadUrl(messageUrl);
    }

    @OnClick(R.id.ib_back)
    public void onClick() {
        finish();
    }

    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setLoadsImagesAutomatically(true);

        if (NetUtils.isNetWorkConnectted(DiaryApplication.mInstance)) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//根据cache-control决定是否从网络上取数据。
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//没网，则从本地获取，即离线加载
        }
        webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        webSettings.setDatabaseEnabled(true);   //开启 database storage API 功能
        webSettings.setAppCacheEnabled(true);//开启 Application Caches 功能

        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        webSettings.setAppCachePath(cacheDirPath);

        mWebView.setWebViewClient(new CustomWebClient());
        mWebView.setWebChromeClient(new CustomChromeClient());
    }

    private class CustomWebClient extends WebViewClient {

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            mProgress.setVisibility(View.GONE);
            super.onPageFinished(view, url);
        }
    }


    private class CustomChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress > 60 && isFirst) {
                alreadyReadMsg();
            }
            mProgress.setProgress(newProgress);
            super.onProgressChanged(view, newProgress);
        }
    }


    private void alreadyReadMsg() {
        isFirst = false;
        User user = DiaryApplication.mInstance.getmUser();
        if (user == null) {
            return;
        }
        String userToken = user.getUserToken();
        NetWork.getInstance()
                .getApiService(IUserApi.class)
                .readMessage(messageId, userToken, Constant.OSTYPE)
                .compose(RxSchedulers.<HttpResult<Object>>io_main())
                .subscribe(new Observer<HttpResult<Object>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        Logger.e("onError");
                    }

                    @Override
                    public void onNext(HttpResult<Object> objectHttpResult) {
//                        Logger.e("onNext");
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }
}
